const {
    getRoleListServe,
    addRoleServe,
    updateRoleServe,
    getRoleById,
    deleteRoleServe,
    getRoleByJobTitle
} = require("../serve/role.serve")

class RoleController {
    async getRoleList(ctx) {
        try {
            const res = await getRoleListServe(ctx);
            ctx.body = {
                status: 0,
                data: {
                    total: res.total,
                    pageSize: res.pageSize,
                    pageNum: res.pageNum,
                    pageData: res.data
                },
                msg: '获取列表成功'
            }
        } catch (e) {
            ctx.body = {
                status: 1,
                msg: e.message,
                data: null
            }
        }
    }

    async addRole(ctx) {
        const permissionButtons = ctx.state.permissionButtons;
        if (!permissionButtons.includes('btn.Role.add')) {
            return ctx.body = {
                status: 1,
                msg: '无权限',
            }
        }
        const {jobTitle} = ctx.request.body;
        const {id: createdByUserId} = ctx.state.user;
        try {
            const res = await getRoleByJobTitle(jobTitle)
            if (res) {
                throw({message: '该职位已存在'})
            }
            await addRoleServe(jobTitle, createdByUserId)
            ctx.body = {
                status: 0,
                msg: '添加角色成功',
                data: null
            }
        } catch (e) {
            ctx.body = {
                status: 1,
                msg: e.message,
                data: null
            }
        }
    }

    async updateRole(ctx) {
        const {jobTitle} = ctx.request.body;
        const {id} = ctx.params;
        const res = await getRoleById(id)
        if (!res) {

            throw({message: '未查询到对应Id的数据'})
        }
        try {
            await updateRoleServe(jobTitle, id)
            ctx.body = {
                state: 0,
                msg: '更新角色成功',
                data: null
            }
        } catch (e) {
            ctx.body = {
                status: 1,
                msg: e.message,
                data: null
            }
        }
    }

    async deleteRole(ctx) {
        const {id} = ctx.params;
        const permissionButtons = ctx.state.permissionButtons;
        if (!permissionButtons.includes('btn.Role.remove')) {
            return ctx.body = {
                status: 1,
                msg: '无权限',
            }
        }
        try {
            const res = await getRoleById(id);
            if (res.length === 0) {
                throw({message: '未找到id对应的数据'})
            }
            const isDelete = await deleteRoleServe(id)
            ctx.body = {
                status: 0,
                msg: '删除成功',
                data: isDelete
            }
        } catch (e) {
            ctx.body = {
                status: 1,
                msg: e.message
            }
        }
    }
}

module.exports = new RoleController()
